/*
 * @Author: wangtao
 * @Date: 2020-06-29 16:32:41
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-05-25 15:34:25
 * @Description: file content
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Modal,
  Text,
  TouchableOpacity,
  PixelRatio,
  ScrollView,
} from 'react-native';
import {
  mainBgColorLightGray,
  mainBgColorWhite,
  fontColorRed,
  fontColorBlack,
  fontColorLightGray,
  fontColorCoffee,
  screenWidth,
  px2dp,
  screenHeight,
  splitLineColorLightGray,
  fontColorSecDeepGray,
  mainBgColorBlack,
} from '../../../../../common/styles';
import { Button, msg } from '../../../../../common';
import SelectItem from './select-item';
import {
  allTransportType,
  allCarModel,
  allCarLength,
  getTruckType,
} from '../../../../../api/source-release';

const { Submit } = Button;

export default class CarNeed extends Component {
  constructor(props) {
    super(props);
    this.state = {
      transportationTypes: [], // 用车类型 接口请求到的源数据
      transportationType: [], // 用车类型 1.整车 2.零担 3.快运 选中的用车类型 code
      transportationTypeName: [], // 用车类型 1.整车 2.零担 3.快运 选中的用车类型 name
      truckTypes: [], // 车型选项 接口请求到的源数据
      truckTypeList: [], // 选择的车型的id
      truckTypeListName: [], // 选择的车车型的名字
      truckLengths: [], // 车长选项 接口请求到的源数据
      truckLengthList: [], // 选择的车长 id
      isSubmit: false,
    };
  }

  componentDidMount() {
    const { supply } = this.props;
    const { transportationType, transportationTypeName, truckTypeList, truckLengthList } = supply;

    let truckTypeListArr = truckTypeList.map(item => {
      return item.id;
    });

    let truckLengthListArr = truckLengthList.map(item => {
      return item.id;
    });

    // 获取所有用车的类型
    allTransportType().then(res => {
      if (res.success) {
        this.setState({
          transportationTypes: res.data,
          transportationType: transportationType ? [transportationType] : [res.data[0].code],
          transportationTypeName: transportationTypeName ? [transportationTypeName] : [res.data[0].name],
        });
      }
    });

    // 获取车型
    getTruckType().then(res => {
      if (res.success) {
        this.setState({
          truckTypes: res.data,
          truckTypeList: truckTypeList.length ? truckTypeListArr : [res.data[1].id], // 是否有已选择的车型 若无则默认选中第一个
          truckLengthList: truckLengthListArr,
        }, () => {
          const { truckTypeList } = this.state;
          this.handTruckleLengthList(truckTypeList);
        });
      }
    });
  }

  /**
   * @values 选中的车型id
   */
  handTruckleLengthList = (values = []) => {
    const { truckTypes, truckLengthList } = this.state;

    let truckLengthsArr = []; // 选中的车型的车长数据 赋值给 truckLengths
    let truckLengthListArr = truckLengthList; // 选中的车长id 赋值给 truckLengthList

    truckTypes.map(item => { // 找到选中的车型的并且有车长的车长数据
      if (values.includes(item.id) && item.list.length > 0) {
        truckLengthsArr.push(item.list);
      }
    });

    truckLengthsArr = truckLengthsArr.flat().reduce((prev, element) => {
      if (!prev.find(el => el.id === element.id)) {
        prev.push(element);
      }
      return prev;
    }, []);

    console.log('truckLengthsArr');
    console.log(truckLengthsArr);

    if (truckLengthsArr.length && !truckLengthListArr.length) {
      truckLengthListArr = [truckLengthsArr[0].id];
    }

    this.setState({
      truckLengths: truckLengthsArr,
      truckLengthList: truckLengthListArr,
    });
  }

  render() {
    const {
      transportationType,
      transportationTypes,
      truckTypes,
      truckTypeList,
      truckLengths,
      truckLengthList,
      isSubmit,
    } = this.state;

    const { onChangeModal } = this.props;
    return (
      <Modal
        animationType='slide'
        transparent
        visible
        onRequestClose={() => {
          onChangeModal({ type: 'carNeedIsShow', val: false });
          // msg.emit('router: back');
        }}
        onShow={() => {
        }}
      >
        <TouchableOpacity
          style={styles.mask}
          onPress={() => {
            onChangeModal({ type: 'carNeedIsShow', val: false });
          }}
        />
        <View style={styles.infoContainer}>
          <View style={styles.header}>
            <TouchableOpacity
              style={styles.cancel}
              onPress={() => {
                onChangeModal({ type: 'carNeedIsShow', val: false });
              }}
            >
              <Text style={{ fontSize: px2dp(32), color: fontColorSecDeepGray }}>
                取消
              </Text>
            </TouchableOpacity>
            <Text
              style={{
                fontSize: px2dp(32),
                color: fontColorBlack,
                fontWeight: 'bold',
              }}
            >
              用车需求
            </Text>
            <Submit
              text='确定'
              boxStyle={{
                width: px2dp(104),
                height: px2dp(60),
                borderRadius: px2dp(8),
                position: 'absolute',
                right: px2dp(28),
              }}
              disabled={false}
              onClick={() => {
                this.submit();
              }}
            />
          </View>
          {/* 包装方式 */}
          <ScrollView
            style={styles.editContainer}
            showsVerticalScrollIndicator={false}
          >
            <View style={styles.packing}>
              <Text
                style={{
                  fontSize: px2dp(28),
                  fontWeight: 'bold',
                  color: mainBgColorBlack,
                }}
              >
                用车类型
              </Text>
              <View style={styles.packingSelect}>
                {!!transportationTypes.length &&
                transportationTypes.map((item, index) => {
                  return (
                    <SelectItem
                      key={`transportationType${index}`}
                      name={item.name}
                      value={item.code}
                      type='transportationType'
                      activeVal={transportationType}
                      maxLength={1}
                      onChange={(type, value) => {
                        this.onChange(type, [value]);
                        this.onChange('transportationTypeName', [item.name]);
                      }}
                    />
                  );
                })}
              </View>
            </View>

            <View style={styles.packing}>
              <Text
                style={{
                  fontSize: px2dp(28),
                  fontWeight: 'bold',
                  color: mainBgColorBlack,
                }}
              >
                车型
                <Text
                  style={{
                    fontSize: px2dp(28),
                    fontWeight: 'normal',
                    color:
                      !isSubmit || truckTypeList.length > 0
                        ? fontColorSecDeepGray
                        : 'red',
                  }}
                >
                  (必选)
                </Text>
              </Text>
              <View style={styles.packingSelect}>
                {!!truckTypes.length &&
                truckTypes.map((item, index) => {
                  return (
                    <SelectItem
                      key={`truckTypeList${index}`}
                      name={item.name}
                      type='truckTypeList'
                      value={item.id}
                      activeVal={truckTypeList}
                      maxLength={3}
                      onChange={(type, value) => {
                        this.handTruckleLengthList(value);
                        this.onChange(type, value);
                      }}
                    />
                  );
                })}
              </View>
            </View>

            <View style={[styles.packing, { paddingBottom: 40 }]}>
              <Text
                style={{
                  fontSize: px2dp(28),
                  fontWeight: 'bold',
                  color: mainBgColorBlack,
                }}
              >
                车长
                <Text
                  style={{
                    fontSize: px2dp(28),
                    fontWeight: 'normal',
                    color:
                      !isSubmit || truckLengthList.length > 0
                        ? fontColorSecDeepGray
                        : 'red',
                  }}
                >
                  (必选)
                </Text>
              </Text>
              <View style={styles.packingSelect}>
                {!!truckLengths.length &&
                truckLengths.map((item) => {
                  return (
                    <SelectItem
                      key={`truckLengthList${item.id}`}
                      name={item.name}
                      type='truckLengthList'
                      value={item.id}
                      activeVal={truckLengthList}
                      maxLength={3}
                      onChange={(type, value) => {
                        this.onChange(type, value);
                      }}
                    />
                  );
                })}
              </View>
            </View>
          </ScrollView>
        </View>
      </Modal>
    );
  }

  // 改变
  onChange = (type, val) => {
    this.setState({ [type]: val });
  };

  // 提交
  submit = () => {
    const {
      isSubmit,
      transportationType,
      transportationTypes,
      truckTypeList,
      truckLengthList,
      transportationTypeName,
      truckLengths,
      truckTypes,
    } = this.state;
    const { onChangeModal, onChangeVal } = this.props;
    if (
      !transportationType.length ||
      !truckTypeList.length ||
      !truckLengthList.length
    ) {
      this.setState({ isSubmit: true });
      return;
    }

    // 车型
    let truckTypeListArr = [];
    truckTypeList.forEach(e => {
      truckTypes.forEach(item => {
        if (e == item.id) {
          truckTypeListArr.push(item);
        }
      });
    });
    let truckTypeListName = truckTypeListArr.map(item => {
      return item.name;
    });
    // 车长
    let truckLengthListArr = [];
    truckLengthList.forEach(e => {
      truckLengths.forEach(item => {
        if (e == item.id) {
          truckLengthListArr.push(item);
        }
      });
    });
    let truckLengthListName = truckLengthListArr.map(item => {
      return item.name;
    });

    onChangeVal({
      type: 'supply',
      val: {
        transportationType: transportationType[0],
        truckTypeList: truckTypeListArr,
        truckLengthList: truckLengthListArr,
        carNeedName: [...transportationTypeName, ...truckTypeListName, ...truckLengthListName].join(',')
      },
    });
    onChangeModal({ type: 'carNeedIsShow', val: false });
  };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
  },
  mask: {
    width: screenWidth,
    height: screenHeight,
    backgroundColor: 'rgba(0,0,0,0.2)',
    position: 'absolute',
    left: 0,
    top: 0,
  },
  infoContainer: {
    width: screenWidth,
    maxHeight: 0.6 * screenHeight,
    backgroundColor: mainBgColorWhite,
    position: 'absolute',
    bottom: 0,
    left: 0,
    borderRadius: px2dp(12),
    overflow: 'hidden',
    zIndex: 10,
  },
  header: {
    width: screenWidth,
    height: px2dp(108),
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderColor: splitLineColorLightGray,
  },
  cancel: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: 80,
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  packing: {
    marginTop: px2dp(48),
  },
  packingSelect: {
    marginTop: px2dp(24),
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-start',
  },
  selectItem: {
    width: px2dp(218),
    height: px2dp(72),
    backgroundColor: mainBgColorLightGray,
    borderRadius: px2dp(8),
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: px2dp(16),
    marginRight: px2dp(10),
  },
  editContainer: {
    paddingHorizontal: px2dp(32),
    paddingBottom: px2dp(100),
  },
});
